package cn.nexd.app.collector.presenter.network;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

import cn.nexd.utils.framework.error.NexdCrashException;

/**
 * Created by wangxu on 16/12/1.
 */

public class FileRequest extends Request<byte[]> {

    private Response.Listener<byte[]> listener;

    public static final Object sDecodeLock = new Object();

    public FileRequest(String url, Response.Listener<byte[]> listener, Response.ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = listener;
    }


    @Override
    protected Response<byte[]> parseNetworkResponse(NetworkResponse networkResponse) {
        synchronized (sDecodeLock) {

            try {

                if (networkResponse.data == null) {
                    return Response.error(new ParseError(networkResponse));
                } else {
                    return Response.success(networkResponse.data, HttpHeaderParser.parseCacheHeaders(networkResponse));
                }
            } catch (OutOfMemoryError e) {
                VolleyLog.e("Caught OOM for %d byte , url = &s", networkResponse.data.length, getUrl());
                NexdCrashException.getInstance().reportException(e);
                return Response.error(new ParseError(e));
            }
        }
    }

    @Override
    protected void deliverResponse(byte[] bytes) {
        if (this.listener != null) {
            this.listener.onResponse(bytes);
        }
    }


    @Override
    protected void onFinish() {
        super.onFinish();
        listener = null;
    }
}
